import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { routerRedux, Route, Switch } from 'dva/router';
import { Form, Input, Select, Button, Modal } from 'antd';
import StandardTable from '@/components/StandardTable';
import AdButton from '@/components/AdButton';
import ETCDetails from './ETCDetails';
import SelectForm from '@/components/SelectForm';
import ManageList from '@/components/ManageList';
import TableButtons from '@/components/TableButtons';
import AdSearch from '@/components/AdSearch';
import AdSelect from '@/components/AdSelect';
import RightDraw from '@/components/RightDraw';
import prompt from '@/components/Prompt';
import RechargeForm from './RechargeForm';
import SearchSelect from '@/components/SearchSelect';
import { columns1 } from '@/pages/Common/common';
import { formateDateToMin } from '@/utils/common';
import { codes } from './utils';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
const confirm = Modal.confirm;

@ManageList
@connect(({ manageEtc, common, component, loading }) => ({
  manageEtc,
  searchValue: component.searchValue,
  ownCompany: common.ownCompany,
  loading: loading.effects['manageEtc/ETCList'],
  dictObject: common.dictObject,
}))
@Form.create()
export default class ETCList extends Component {
  state = {
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    stepFormValues: {},
    visible: false,
    rechargeVisible: false,
    checkId: '',
    checkIds: [],
    formValues: {},
    isAbled: '',
    cardNo: '',
    cars: [],
    rowDetails: {},
  };

  className = 'ETCList';

  columns = [
    {
      title: 'ETC卡号',
      dataIndex: 'cardNo',
      render: (text, record) => (
        <AdButton
          mode="a"
          onClick={e => this.showDetail(e, record)}
          text={text}
          code={codes.showDetail}
        />
      ),
      fixed: this.props.isMobile ? false : true,
    },
    {
      title: '主车牌',
      dataIndex: 'cartPlateNo',
    },
    {
      title: '所属公司',
      dataIndex: 'ownCompanyName',
      render: text => <span title={text}>{text}</span>,
      width: 250,
    },
    {
      title: '币种',
      dataIndex: 'currencyType',
      render: text => (
        <AdSelect onlyRead={true} value={text} data={this.props.dictObject['currency-type']} />
      ),
      width: 100,
    },
    {
      title: '剩余金额',
      dataIndex: 'balance',
    },
    {
      title: '状态',
      dataIndex: 'beActive',
      render: (text, record) => <span>{text ? '启用' : '禁用'}</span>,
      width: 100,
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
  ];
  componentDidMount() {
    this.getETCList();
    // 查询字典：
    // 发售公司
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'sale-company' },
    });
    //币种：
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'currency-type' },
    });
  }
  componentWillReceiveProps(nextProps) {
    const {
      dictObject,
      manageEtc: { ETCList },
    } = nextProps;
    if (dictObject['sale-company'] && ETCList.list) {
      dictObject['sale-company'].map(v => {
        ETCList.list.map((v1, i1) => {
          if (v.code === v1.sellCompanyCode) {
            ETCList.list[i1].sellCompanyCode = v.value;
          }
        });
      });
    }
  }

  onRef = ref => {
    this.child = ref;
  };

  getETCList = (params = {}) => {
    const { dispatch, searchValue } = this.props;
    dispatch({
      type: 'manageEtc/ETCList',
      payload: params,
      callback: data => {
        if (!data) return;
        let valueList = [];
        data.map(v => {
          const labels = ['updateBy', 'createBy'];
          labels.map(item => {
            if (v[item] && !valueList.includes(v[item])) {
              valueList.push(v[item]);
              !searchValue[v[item]] &&
                dispatch({
                  type: 'component/querySearchValue',
                  payload: { params: { loginName: v[item] }, url: 'tms/tms-etc/selectEtcUser_s' },
                });
            }
          });
        });
      },
    });
  };

  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
      cars: [],
    });
    this.getETCList();
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleSelectRows = rows => {
    // console.log('选择', rows);
    let ids = [];
    if (Array.isArray(rows) && rows.length > 0) {
      rows.map((item, i) => {
        ids.push(item.id);
      });
    }
    this.setState({
      selectedRows: rows,
      checkIds: ids,
    });
  };

  //查询
  handleSearch = values => {
    // if (!values) {
    //   return;
    // }
    const { ...value } = values;
    const { cars } = this.state;
    if (cars.length > 0) {
      const vehicleId = cars.map(v => {
        return v.id;
      });
      value.vehicleId = vehicleId.join(',');
    } else {
      value.vehicleId = '';
    }
    this.setState({
      formValues: value,
    });
    this.getETCList(value);
  };

  //新建
  handleAdd = () => {
    // 设置id
    const { dispatch } = this.props;
    // dispatch({
    //   type: 'manageEtc/setId',
    //   payload: { id: -1 },
    // });
    router.push(`/carBasic/manageEtc/ETCList/addETC`);
  };
  //编辑：
  handleEdit = () => {
    router.push(`/carBasic/manageEtc/ETCList/editETC/${this.state.checkId}`);
    this.closeDetail();
  };
  // 分页操作：改参数
  handleStandardTableChange = param => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      ...formValues,
      ...param,
    };
    this.getETCList(params);
  };

  //详情：
  showDetail = (e, record) => {
    e.stopPropagation();
    const { dispatch } = this.props;
    const { id, cardNo } = record;

    dispatch({
      type: 'manageEtc/etcDetails',
      payload: { id: id },
      callback: res => {
        this.setState({
          isAbled: res.beActive == true || res.beActive == '启用' ? true : false,
        });
      },
    });
    dispatch({
      type: 'manageEtc/etcChangeList',
      payload: { etcNo: cardNo },
    });

    this.setState(
      {
        checkId: id,
        cardNo: cardNo,
        rowDetails: record,
      },
      () => {
        this.setState({
          visible: true,
        });
      }
    );
  };

  closeDetail = () => {
    this.setState({
      visible: false,
    });
  };
  getValue = values => {
    this.setState({
      cars: values,
    });
  };

  //启用、禁用：
  etcCardStatus = (type, isSingle) => {
    // console.log('启用禁用');
    const { dispatch } = this.props;
    const { checkIds, checkId, formValues } = this.state;
    let urlType = 'manageEtc/enableTmsEtcCard';
    if (type == 'disabled') {
      urlType = 'manageEtc/disabledTmsEtcCard';
    }

    dispatch({
      type: urlType,
      payload: { ids: isSingle ? [checkId] : checkIds },
      callback: res => {
        this.getETCList(formValues);
        prompt({ content: res.message });
        if (isSingle) {
          this.props.dispatch({
            type: 'manageEtc/etcDetails',
            payload: { id: checkId },
            callback: res => {
              this.setState({
                isAbled: res.beActive == true || res.beActive == '启用' ? true : false,
              });
            },
          });
        }
      },
    });
  };

  GoRechange = type => {
    const { checkIds, selectedRows, checkId, cardNo } = this.state;
    if (type == 'detail') {
      this.setState({
        visible: false,
        rechargeVisible: true,
      });
    } else {
      router.push({
        pathname: `/carBasic/manageEtc/ETCList/recharge`,
      });
    }
  };
  handleCancel = e => {
    this.setState({
      rechargeVisible: false,
    });
  };
  handleRechargeOK = () => {
    this.child.operatePaneButton();
  };
  getChildValue = data => {
    if (data == 'false') {
      this.handleCancel();
    }
  };

  //删除
  removeRecord = () => {
    const { dispatch } = this.props;
    const { checkId, visible, formValues } = this.state;
    confirm({
      title: '确定要删除这条数据吗？',
      content: ' ',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'manageEtc/deleteEtc',
          payload: { id: checkId },
          callback: () => {
            this.setState({ visible: false, selectedRows: [] });
            this.getETCList(formValues);
          },
        });
      },
    });
  };

  render() {
    const {
      loading,
      manageEtc: { ETCList, etcDetails },
      form,
      isMobile,
      dictObject,
      ownCompany,
    } = this.props;
    const { getFieldDecorator } = form;
    const {
      selectedRows,
      updateModalVisible,
      stepFormValues,
      isAbled,
      checkId,
      cardNo,
      visible,
      rechargeVisible,
      rowDetails,
      expandForm,
    } = this.state;

    const selectDetails = etcDetails[checkId];
    const firstFormItem = (
      <FormItem label="ETC卡号">
        {getFieldDecorator('cardNo')(<Input placeholder="请输入" />)}
      </FormItem>
    );
    const secondFormItem = (
      <FormItem label="状态">
        {getFieldDecorator('beActive')(
          <Select placeholder="请选择" style={{ width: '100%' }} allowClear={true}>
            <Option value="">请选择</Option>
            <Option value="true">启用</Option>
            <Option value="false">禁用</Option>
          </Select>
        )}
      </FormItem>
    );

    // secondForm 参数
    const otherFormItem = [
      [
        <FormItem label="车牌号">
          {getFieldDecorator('vehicleId')(
            <SearchSelect
              dataUrl="tms/tms-etc/selectEtcVehicle"
              // url="tms/tms-etc/selectVehicleView_s" // selectedData只只有id时需要传url
              selectedData={this.state.cars} // 选中值
              multiple={false} // 是否多选
              showValue="cartPlateOneNo"
              searchName="cartPlate"
              columns={columns1} // 表格展示列
              onChange={this.getValue} // 获取选中值
              scrollX={480}
              id="etcList_1"
            />
          )}
        </FormItem>,
      ],
      [
        <FormItem label="所属公司">
          {getFieldDecorator('mdsCompanyId')(
            <Select
              allowClear={true}
              showSearch
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              placeholder="请选择"
              style={{ width: '100%' }}
            >
              <Option value="">请选择</Option>
              {ownCompany &&
                ownCompany.map((v, i) => {
                  return (
                    <Option key={i} value={v.customerCode}>
                      {v.customerName}
                    </Option>
                  );
                })}
            </Select>
          )}
        </FormItem>,
        'operatorButtons',
      ],
    ];
    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      otherFormItem,
      form,
      code: codes.select,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: this.toggleForm,
    };
    const tableButtonsParams = {
      show: true,
      handleAdd: this.handleAdd,
      code: codes.add,
      buttons: (
        <Button.Group>
          <AdButton
            onClick={() => this.etcCardStatus('disabled')}
            disabled={selectedRows.length > 0 ? false : true}
            text="禁用"
            code={codes.disable}
          />
          <AdButton
            onClick={() => this.etcCardStatus('abled')}
            disabled={selectedRows.length > 0 ? false : true}
            text="启用"
            code={codes.enable}
          />
          <AdButton onClick={() => this.GoRechange()} text="充值" code={codes.rechage} />
        </Button.Group>
      ),
      selectedRows: selectedRows,
    };

    const rightDrawParams = {
      isMobile,
      visible,
      title: 'ETC详情',
      closeDetail: this.closeDetail,
      code: codes.showDetail,
      buttons: (
        <span>
          <AdButton
            onClick={() => this.removeRecord(1)}
            text="删除"
            type="danger"
            ghost
            code={codes.remove}
          />
          <Button.Group style={{ marginLeft: 8 }}>
            {isAbled && (
              <AdButton
                onClick={() => this.etcCardStatus('disabled', 1)}
                text="禁用"
                code={codes.disable}
              />
            )}
            {!isAbled && (
              <AdButton
                onClick={() => this.etcCardStatus('abled', 1)}
                text="启用"
                code={codes.enable}
              />
            )}
            <AdButton onClick={() => this.GoRechange('detail')} text="充值" code={codes.rechage} />
            <AdButton onClick={this.handleEdit} type="primary" text="编辑" code={codes.edit} />
          </Button.Group>
        </span>
      ),
    };

    return (
      <Fragment>
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          selectedRows={selectedRows}
          loading={loading}
          data={ETCList}
          columns={this.columns}
          onSelectRow={this.handleSelectRows}
          expandForm={expandForm}
          className={this.className}
          onPaginationChange={this.handleStandardTableChange}
          code={codes.page}
        />
        <RightDraw {...rightDrawParams}>
          <ETCDetails checkId={checkId} isMobile={isMobile} />
        </RightDraw>
        <Modal
          title={`ETC充值`}
          visible={rechargeVisible}
          onOk={this.handleRechargeOK}
          onCancel={this.handleCancel}
          width={720}
          style={{ top: 20 }}
        >
          <RechargeForm
            type="modal"
            onRef={this.onRef}
            checkId={checkId}
            cardNo={cardNo}
            rowDetails={rowDetails}
            pfn={this.getChildValue.bind(this)}
          />
        </Modal>
      </Fragment>
    );
  }
}
